package com.elektronikforumet.camalert;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class DatabaseManagerActivity extends Activity implements OnClickListener, CameraService.Callback {
	
	private Button mWsSync  = null;
	private Button mFileImport = null;
	private ProgressDialog mWsProgressDialog = null;
	private TextView mSyncDate = null;
	private Handler mHandler = null;
	
	 private static final int HANDLER_MSG_SHOW_PROGRESS = 1;
     private static final int HANDLER_MSG_UPDATE_DATABASE = 2;
     private static final int HANDLER_MSG_HIDE_PROGRESS = 3;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.database_manager);
        
        CameraDatabase db = new CameraDatabase(getApplicationContext());
        db.open();
        
        mSyncDate = (TextView)findViewById(R.id.ws_sync_date);
        TextView numCams = (TextView)findViewById(R.id.ws_num_cams);
        int cams  = db.countWebserviceCameras();
        if(cams > 0) {
        	numCams.setText(String.valueOf(cams));
        }
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        long syncDate = prefs.getLong(EditPreferences.PREFS_LATEST_WS_SYNC, -1);
        if(syncDate > 0) {
        	Date date = new Date(syncDate);
        	mSyncDate.setText(date.toLocaleString());
        }
        
        mWsSync = (Button)findViewById(R.id.ws_sync_button);
        mWsSync.setOnClickListener(this);
        
        mFileImport = (Button)findViewById(R.id.file_import_button);
        mFileImport.setOnClickListener(this);
        
        // Handler for thread-safe opening of progress dialog
        mHandler = new Handler(new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) {
				switch (msg.what) {
				case HANDLER_MSG_SHOW_PROGRESS:
					mWsProgressDialog = ProgressDialog.show(DatabaseManagerActivity.this, getString(R.string.synchronizing), getString(R.string.check_for_updates), true, false);
					break;
				case HANDLER_MSG_UPDATE_DATABASE:
					if(mWsProgressDialog != null) {
						mWsProgressDialog.setMessage(getString(R.string.updating_database));
					}
					break;
				case HANDLER_MSG_HIDE_PROGRESS:
					if(mWsProgressDialog != null) {
						mWsProgressDialog.dismiss();
						mWsProgressDialog = null;
					}
					break;
				}
				return false;
			}
		});
        
       
        
        fillFileList(db);
        db.close();
        db = null;
	}
	
	public void fillFileList(CameraDatabase db){
		ListView fileList = (ListView)findViewById(R.id.file_list);
		
		Cursor c = db.fetchallFiles();
    	startManagingCursor(c);
    	
    	String[] from = new String[] { CameraDatabase.COLUMN_FILE_NAME, CameraDatabase.COLUMN_FILE_DATE};
    	int[] to = new int[] { R.id.file_name, R.id.file_date};
    	
    	SimpleCursorAdapter files = null;
    	try {
    		files = new SimpleCursorAdapter(this, R.layout.file_row, c, from, to);
    	} catch (Exception e) {
    		Log.d("CamAlert", "Error", e);
		}
    	fileList.setAdapter(files);
	}

	@Override
	public void onClick(View v) {
		if(v == mWsSync) {
			// Handle webservice sync
		
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
	        long syncDate = prefs.getLong(EditPreferences.PREFS_LATEST_WS_SYNC, -1);
			
	        Date since = new Date(syncDate);
			
	        if(mHandler != null) {
	        	mHandler.sendEmptyMessage(HANDLER_MSG_SHOW_PROGRESS);
	        }
	        
//	        mWsProgressDialog = ProgressDialog.show(this, getString(R.string.synchronizing), getString(R.string.check_for_updates), true, false);
	        
	        CameraService cs = new CameraService(this);
	        cs.beginFetchChangedCameras(since);
			
		} else if(v == mFileImport) {
			// Handle file import
			
			Intent i = new Intent(getApplicationContext(), SelectFileActivity.class);
			startActivityForResult(i, REQUEST_SELECT_FILE);
		}
	}
	
	private static final int REQUEST_SELECT_FILE = 999;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == REQUEST_SELECT_FILE && resultCode == RESULT_OK) {
			// TODO: Get intent and parse file;
		}
	}

	@Override
	protected void onPause() {
		
		super.onPause();
	}

	@Override
	public void cameraServiceError(String error, Throwable e) {
		if(mWsProgressDialog != null) {
			mWsProgressDialog.dismiss();
		}
		
		Log.e("cameraServiceError", error, e);
	}

	@Override
	public void cameraServiceReceived(ArrayList<SpeedCamera> cams) {
		
		// Store sync date
		// TODO: Compensate for timezone
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        Editor editor = prefs.edit();
        editor.putLong(EditPreferences.PREFS_LATEST_WS_SYNC, System.currentTimeMillis());
        editor.commit();
        
        if(mHandler != null) {
        	mHandler.sendEmptyMessage(HANDLER_MSG_UPDATE_DATABASE);
        }
        
		CameraDatabase db = new CameraDatabase(this);
		db.open();

		int result;
		int inserted = 0;
		int updated = 0;
		int failed = 0;
		int deleted = 0;
		for(SpeedCamera sc : cams) {
			result = db.updateCamera(sc);
			
			switch(result) {
			case CameraDatabase.UPDATE_RESULT_INSERTED: inserted++; break;
			case CameraDatabase.UPDATE_RESULT_FAILED: failed++; break;
			case CameraDatabase.UPDATE_RESULT_DELETED: deleted++; break;
			case CameraDatabase.UPDATE_RESULT_UPDATED : updated++; break;
			}
		}
		
		db.close();
		db = null;
		
		if(mHandler != null) {
			mHandler.sendEmptyMessage(HANDLER_MSG_HIDE_PROGRESS);
		}
		
		// TODO: Visa resultat av updatering.
		
		finish();
	}
}
